package sudoku;

/**
 * 判断是否为数独矩阵:
 *  每行元素不得重复，并且每列元素不得重复，并且每个小方阵也不得重复
 *  https://blog.csdn.net/qq_43157982/article/details/84142484
 */
public class Judge {
    public static void main(String[] args) {
        int grid[][]={
                {5,3,4,6,7,8,9,1,2},
                {6,7,2,1,9,5,3,4,8},
                {1,9,8,3,4,2,5,6,7},
                {8,5,9,7,6,1,4,2,3},
                {4,2,6,8,5,3,7,9,1},
                {7,1,3,9,2,4,8,5,6},
                {9,6,1,5,3,7,2,8,4},
                {2,8,7,4,1,9,6,3,5},
                {3,4,5,2,8,6,1,7,9}};
        if(Imp1.isSudoku(grid)){
            System.out.println("是 数独");
        }else{
            System.out.println("不是数独");
        }
    }
    static class Imp1{
        public static boolean isSudoku(int[][] grid){
            return isAllCell(grid) && isAllCol(grid) && isAllRow(grid);
        }
        private static boolean isAllCell(int[][] grid) {
            //找基点
            for (int i = 0; i < 9; i += 3) {
                for (int j = 0; j < 9; j += 3) {
                    //找偏移量，小矩阵
                    boolean[] cell = new boolean[9];
                    for (int x = 0; x < 3; x++) {
                        for (int y = 0; y < 3; y++) {
                            if (!cell[grid[x + i][y + j] - 1]) {
                                cell[grid[x + i][y + j] - 1] = true;
                            } else {
                                return false;
                            }
                        }
                    }
                }
            }
            return true;
        }

        private static boolean isAllCol(int[][] grid) {
            for (int i = 0; i < grid.length; i++) {
                boolean[] row = new boolean[9];
                for (int j = 0; j < grid[i].length; j++) {
                    if (!row[grid[j][i] - 1]) {
                        row[grid[j][i] - 1] = true;
                    } else {
                        return false;
                    }
                }
            }
            return true;
        }


        private static boolean isAllRow(int[][] grid) {
            for (int[] ints : grid) {
                boolean[] row = new boolean[9];
                for (int anInt : ints) {
                    if (!row[anInt - 1]) {
                        row[anInt - 1] = true;
                    } else {
                        return false;
                    }
                }
            }
            return true;
        }
    }
}
